// pages/contacts/contacts.js
//协调事项转交时人员列表
var app = getApp()
var spell = require('../../utils/spell.js')
var utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //流程信息
    authFlag:0,
    taskId:0,
    taskDefKey:'',
    procInsId:0,
    procDefId:0,
    businessId:0,
    businessTable:'',
    primaryId:0,
    authUrl:'',

    allUsers:[],//所有用户信息
    // 当前选择的导航字母
    selected: 0,
    // 选择字母视图滚动的位置id
    scrollIntoView: 'A',
    windowHeight:0,
    // 导航字母
    letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (obj) {
    var that = this
    that.setData({
      authFlag: obj.flag,
      taskId: obj.taskId,
      taskDefKey: obj.taskDefKey,
      procInsId: obj.procInsId,
      procDefId: obj.procDefId,
      businessId: obj.businessId,
      businessTable: obj.businessTable,
      primaryId: obj.id,
      authUrl: obj.authUrl
    })
    that.calcuPostion()
    if (utils.checkNetWorkStatus() == false) {
      console.log('网络错误');
      wx.navigateBack({
        delta: 1
      })
      wx.showToast({
        title: '网络错误请检查',
        duration: 2000,
      })
    } else {
    var url = app.GLOBAL_CONFIG.commonUrl + app.GLOBAL_CONFIG.getOrgAllUser + "?rows=1500",
      cookie = app.globalData.cookie
    utils.getRequest(url, cookie,app, that, function (res, that) {
      if (res.data.rows.length > 0) {
        var dataArr = that.getSortableData(res.data.rows)
        that.setData({
          allUsers: dataArr
        })

      } else {
        wx.navigateBack({
          delta: 1
        })
        wx.showToast({
          title: '获取数据失败，请稍后重试',
          image: '../../images/fail.png'
        })
      }
    },function(res){
      wx.navigateBack({
        delta: 1
      })
      wx.showToast({
        title: '获取数据失败，请稍后重试',
        image: '../../images/fail.png'
      })
    })
  }
  },

  chooseUser:function(e){
    var that = this,
      assignee = e.target.dataset.userid
    console.log("choose user id "+ e.target.dataset.userid)
    wx.showModal({
      title: '提示',
      content: '确定转交给' + e.target.dataset.username+'吗？',
      success: function (res) {
        if (res.confirm) {
          var url = app.GLOBAL_CONFIG.commonUrl + that.data.authUrl + '?isWxApp=true&flag=' + that.data.authFlag + '&taskId=' + that.data.taskId + '&taskDefKey=' + that.data.taskDefKey + '&procInsId=' + that.data.procInsId + '&procDefId=' + that.data.procDefId + '&businessId=' + that.data.businessId + '&businessTable=' + that.data.businessTable + '&id=' + that.data.primaryId + '&assignee=' + assignee,
            cookie = app.globalData.cookie
          console.log("转交审批url " + url)
          if (utils.checkNetWorkStatus() == false) {
            console.log('网络错误');
            wx.showToast({
              title: '网络错误请检查',
              duration: 2000,
            })
          } else {
            utils.postRequest(url, cookie, app, that, function(res,that){
              if (res.data == "success") {
                wx.navigateBack({
                  delta: 2
                })
                wx.showToast({
                  title: '转交成功',
                  icon:'success',
                  duration: 8000
                })
              } else {
                wx.showToast({
                  title: '操作失败，请稍后重试',
                  image: '../../images/fail.png',
                  duration: 2000
                })
              }
            }, function (res) {
              wx.showToast({
                title: '操作失败，请稍后重试',
                image: '../../images/fail.png',
                duration: 2000
              })
            })  
          }
        } else {
          return;
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   // this.onLoad()
    
  },

  getSortableData: function (allUsers){
    var userArr = [], dataArr =[], str =[]
    for (var h = 0; h < allUsers.length;h++) {
      userArr[h] = [spell.py.getSpell(allUsers[h].name), allUsers[h]]
    }
    userArr = userArr.sort();
    for (var i = 0; i < 26; i++) {
      var upperchar = String.fromCharCode(65 + i);
      var flag = false;
      dataArr.push({ 'groupName': upperchar, 'users': [] });
      for (var j = 0; j < allUsers.length; j++) {
        var firstchar = userArr[j][0].substring(0, 1).toLocaleUpperCase ()// getSubstr(userArr[j][0]);
        if (upperchar == firstchar) {
          flag = true;
          dataArr[i]['users'].push(userArr[j][1])
        }
      }
      if (flag == false) {
        str.push(upperchar)
      }
    }

    for (var k = 0; k < str.length; k++) {
      for (var i = 0; i < dataArr.length; i++) {
        if (dataArr[i]['groupName'] == str[k]) {
          dataArr.splice(i, 1);
        }
      }
    }
   
    return dataArr;

    },
  calcuPostion:function(){
    const res = wx.getSystemInfoSync(),
      letters = this.data.letters;
    // 设备信息
    this.setData({
      windowHeight: res.windowHeight,
      windowWidth: res.windowWidth,
      pixelRatio: res.pixelRatio
    });
    // 第一个字母距离顶部高度，css中定义nav高度为94%，所以 *0.94
    const navHeight = this.data.windowHeight * 0.94, // 
      eachLetterHeight = navHeight / 26,
      comTop = (this.data.windowHeight - navHeight) / 2,
      temp = [];

    this.setData({
      eachLetterHeight: eachLetterHeight
    });

    // 求各字母距离设备左上角所处位置

    for (let i = 0, len = letters.length; i < len; i++) {
      const x = this.data.windowWidth - (10 + 50) / this.data.pixelRatio,
        y = comTop + (i * eachLetterHeight);
      temp.push([x, y]);
    }
    this.setData({
      lettersPosition: temp
    })
  },  

  tabLetter(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selected: index,
      scrollIntoView: index
    })

    this.cleanAcitvedStatus();
  },
  // 清除字母选中状态
  cleanAcitvedStatus() {
    setTimeout(() => {
      this.setData({
        selected: 0
      })
    }, 500);
  },
  touchmove(e) {
    const x = e.touches[0].clientX,
      y = e.touches[0].clientY,
      lettersPosition = this.data.lettersPosition,
      eachLetterHeight = this.data.eachLetterHeight,
      letters = this.data.letters;
    console.log(y);
    // 判断触摸点是否在字母导航栏上
    if (x >= lettersPosition[0][0]) {
      for (let i = 0, len = lettersPosition.length; i < len; i++) {
        // 判断落在哪个字母区域，取出对应字母所在数组的索引，根据索引更新selected及scroll-into-view的值
        const _y = lettersPosition[i][1], // 单个字母所处高度
          __y = _y + eachLetterHeight; // 单个字母最大高度取值范围
        if (y >= _y && y <= __y) {
          this.setData({
            selected: letters[i],
            scrollIntoView: letters[i]
          });
          break;
        }
      }
    }
  },
  touchend(e) {
    this.cleanAcitvedStatus();
  }
   
 
})